import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Typography, Form, Input, Select, Upload as AntUpload, Card, Tag, Space, message, Divider, Tabs, Button } from 'antd';
import { InboxOutlined, PlusOutlined, EyeOutlined, UploadOutlined } from '@ant-design/icons';
import { auth, torrents } from '../services';

const { Title, Paragraph } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { Dragger } = AntUpload;
const { TabPane } = Tabs;

const UploadTorrent = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [uploadedTorrent, setUploadedTorrent] = useState(null);
  const [coverImage, setCoverImage] = useState(null);
  const [previewTab, setPreviewTab] = useState('1');
  const [messageApi, contextHolder] = message.useMessage();

  // 促销设置样式
  const promotionStyles = {
    container: {
      marginTop: '8px',
      padding: '12px 16px',
      background: 'linear-gradient(135deg, #f6f8fa 0%, #e9ecef 100%)',
      borderRadius: '8px',
      border: '1px solid #e1e8ed',
      fontSize: '13px',
      color: '#666'
    },
    optionContainer: {
      display: 'flex',
      alignItems: 'center',
      padding: '12px 0',
      borderBottom: '1px solid #f0f0f0',
      transition: 'all 0.2s ease'
    },
    iconContainer: {
      fontSize: '24px',
      marginRight: '16px',
      width: '32px',
      height: '32px',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      borderRadius: '50%',
      background: '#f8f9fa'
    },
    titleContainer: {
      flex: 1
    },
    title: {
      fontWeight: 'bold',
      fontSize: '15px',
      marginBottom: '4px',
      lineHeight: '1.2'
    },
    description: {
      fontSize: '12px',
      color: '#666',
      lineHeight: '1.4',
      margin: 0
    }
  };

  // 模拟的文件列表




  // 处理种子文件选择
  const handleTorrentUpload = (file) => {
    if (file && file instanceof File) {
      messageApi.success(`${file.name} 选择成功`);
      setUploadedTorrent(file);
    }

    // 返回false阻止自动上传
    return false;
  };

  // 处理封面图片选择
  const handleCoverImageUpload = (file) => {
    if (file && file instanceof File) {
      messageApi.success(`${file.name} 选择成功`);

      // 将文件转换为URL以供预览
      const reader = new FileReader();
      reader.onload = () => {
        setCoverImage(reader.result);
      };
      reader.onerror = (error) => {
        console.error('图片读取失败:', error);
        messageApi.error('图片读取失败');
      };

      reader.readAsDataURL(file);
    }

    // 返回false阻止自动上传
    return false;
  };

  // 提交表单
  const handleSubmit = async (values) => {
    if (!uploadedTorrent) {
      messageApi.error('请上传种子文件');
      return;
    }

    setLoading(true);

    try {
      // 创建一个FormData对象，匹配后端API要求
      const formData = new FormData();
      formData.append('torrentFile', uploadedTorrent);
      formData.append('name', values.title); // 种子名称
      formData.append('classification', values.classification); // 种子分类字段

      // 处理促销类型：写入category字段，传递实际选择的值
      const promotionValue = values.promotion || 'none'; // 默认为'none'
      formData.append('category', promotionValue); // 促销类型写入category字段

      // 自动生成上传时间戳 (格式: YYYY-MM-DD HH:MM:SS)
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');
      const hours = String(currentDate.getHours()).padStart(2, '0');
      const minutes = String(currentDate.getMinutes()).padStart(2, '0');
      const seconds = String(currentDate.getSeconds()).padStart(2, '0');
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      formData.append('fileTimestamps', formattedDate);

      // 添加comment参数到FormData
      formData.append('comment', values.comment || '');

      console.log('🎯 促销设置:', values.promotion || 'none', '→ category字段:', promotionValue);

      if (coverImage) {
        // 从base64转回Blob
        const byteString = atob(coverImage.split(',')[1]);
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);
        for (let i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }
        const blob = new Blob([ab], { type: 'image/jpeg' });
        formData.append('pictureFile', blob, 'cover.jpg');
      } else {
        // 后端要求pictureFile参数，如果没有封面图片，创建一个空的Blob
        const emptyBlob = new Blob([''], { type: 'image/jpeg' });
        formData.append('pictureFile', emptyBlob, 'empty.jpg');
      }

      const response = await torrents.uploadTorrent(formData);

      console.log('📤 上传响应详情:', response);

      if (response.success) {
        messageApi.success('种子发布成功！您可以在资源中心查看刚上传的种子');

        // 由于后端不返回种子ID，直接跳转到资源中心
        // 用户可以在那里看到刚上传的种子
        setTimeout(() => {
          navigate('/resources');
        }, 1500); // 延迟1.5秒让用户看到成功消息
      } else {
        messageApi.error(response.message || '发布失败');
      }
    } catch (error) {
      console.error('上传种子失败:', error);
      messageApi.error('上传种子失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      {contextHolder}
      <Title level={2}>上传新种子</Title>
      <Paragraph type="secondary">
        上传的种子文件应当符合站点规则，请确保您有权分享这些内容。
      </Paragraph>

      <Tabs
        defaultActiveKey="1"
        activeKey={previewTab}
        onChange={setPreviewTab}
        style={{ marginBottom: 32 }}
      >
        <TabPane tab="上传信息" key="1">
          <Card>
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                classification: '电影',
                promotion: 'none'
              }}
            >
              <Divider orientation="left">种子文件上传</Divider>

              <Form.Item>
                <Dragger
                  name="torrent"
                  multiple={false}
                  beforeUpload={handleTorrentUpload} // 直接在这里处理文件
                  accept=".torrent"
                >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽种子文件到此区域上传</p>
                  <p className="ant-upload-hint">
                    支持单个.torrent文件上传
                  </p>
                </Dragger>
              </Form.Item>



              <Divider orientation="left">基本信息</Divider>

              <Form.Item
                name="title"
                label="标题"
                rules={[{ required: true, message: '请输入种子标题' }]}
              >
                <Input placeholder="种子标题" />
              </Form.Item>



              <Form.Item
                name="classification"
                label="种子分类"
                rules={[{ required: true, message: '请选择种子分类' }]}
              >
                <Select placeholder="选择种子分类">
                  <Option value="电影">电影</Option>
                  <Option value="电视剧">电视剧</Option>
                  <Option value="纪录片">纪录片</Option>
                  <Option value="动漫">动漫</Option>
                  <Option value="音乐">音乐</Option>
                  <Option value="图书">图书</Option>
                  <Option value="软件">软件</Option>
                  <Option value="游戏">游戏</Option>
                  <Option value="其他">其他</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="promotion"
                label={
                  <span style={{ fontSize: '14px', fontWeight: 'bold' }}>
                    🎯 促销设置
                  </span>
                }
                rules={[{ required: true, message: '请选择促销类型' }]}
                extra={
                  <div style={promotionStyles.container}>
                    <div style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}>
                      <span style={{ fontSize: '16px', marginRight: '8px' }}>💡</span>
                      <strong>促销类型说明</strong>
                    </div>
                    <div>选择种子的促销类型，影响用户的上传下载量计算</div>
                    <div style={{ marginTop: '8px', fontSize: '12px', opacity: 0.8 }}>
                      • 双倍上传量：做种时获得2倍上传量奖励<br />
                      • 下载免费：下载该种子不消耗下载量<br />
                      • 无促销：按正常规则计算上传下载量
                    </div>
                  </div>
                }
              >
                <Select
                  placeholder="请选择促销类型"
                  size="large"
                  style={{
                    width: '100%',
                    borderRadius: '8px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
                  }}
                  optionLabelProp="label"
                  dropdownStyle={{
                    borderRadius: '8px',
                    boxShadow: '0 4px 16px rgba(0,0,0,0.15)',
                    border: '1px solid #e1e8ed'
                  }}
                >
                  <Option
                    value="none"
                    label={
                      <span>
                        <span style={{ marginRight: 8 }}>🚫</span>
                        无促销
                      </span>
                    }
                  >
                    <div style={promotionStyles.optionContainer}>
                      <div style={{
                        ...promotionStyles.iconContainer,
                        background: 'linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)'
                      }}>
                        🚫
                      </div>
                      <div style={promotionStyles.titleContainer}>
                        <div style={promotionStyles.title}>
                          无促销
                        </div>
                        <div style={promotionStyles.description}>
                          正常计算上传下载量，无任何优惠
                        </div>
                      </div>
                    </div>
                  </Option>

                  <Option
                    value="double_upload"
                    label={
                      <span>
                        <span style={{ marginRight: 8 }}>⬆️</span>
                        双倍上传量
                      </span>
                    }
                  >
                    <div style={promotionStyles.optionContainer}>
                      <div style={{
                        ...promotionStyles.iconContainer,
                        background: 'linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%)',
                        border: '1px solid #b7eb8f'
                      }}>
                        ⬆️
                      </div>
                      <div style={promotionStyles.titleContainer}>
                        <div style={{
                          ...promotionStyles.title,
                          color: '#52c41a'
                        }}>
                          双倍上传量
                        </div>
                        <div style={promotionStyles.description}>
                          上传量按2倍计算，下载量正常计算
                        </div>
                      </div>
                    </div>
                  </Option>

                  <Option
                    value="free_download"
                    label={
                      <span>
                        <span style={{ marginRight: 8 }}>🆓</span>
                        下载量免费
                      </span>
                    }
                  >
                    <div style={{
                      ...promotionStyles.optionContainer,
                      borderBottom: 'none'
                    }}>
                      <div style={{
                        ...promotionStyles.iconContainer,
                        background: 'linear-gradient(135deg, #fff7e6 0%, #ffd591 100%)',
                        border: '1px solid #ffb84d'
                      }}>
                        🆓
                      </div>
                      <div style={promotionStyles.titleContainer}>
                        <div style={{
                          ...promotionStyles.title,
                          color: '#fa8c16'
                        }}>
                          下载量免费
                        </div>
                        <div style={promotionStyles.description}>
                          下载不计算下载量，上传量正常计算
                        </div>
                      </div>
                    </div>
                  </Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="comment"
                label="种子描述"
                rules={[
                  { max: 200, message: '描述不能超过200字' }
                ]}
                extra="可选，描述种子内容、质量等信息（限制200字以内）"
              >
                <TextArea
                  placeholder="请输入种子描述..."
                  rows={4}
                  maxLength={200}
                  showCount
                />
              </Form.Item>



              <Divider orientation="left">封面图片</Divider>

              <Form.Item
                name="coverImage"
                label="封面图片"
                extra="上传种子的封面图片，建议尺寸为300x450像素"
              >
                <AntUpload
                  name="coverImage"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  beforeUpload={handleCoverImageUpload} // 直接在这里处理文件
                  accept="image/*"
                >
                  {coverImage ? (
                    <img
                      src={coverImage}
                      alt="封面"
                      style={{ width: '100%' }}
                    />
                  ) : (
                    <div>
                      <PlusOutlined />
                      <div style={{ marginTop: 8 }}>上传封面</div>
                    </div>
                  )}
                </AntUpload>
              </Form.Item>

              <Form.Item>
                <Space>
                  <Button
                    type="primary"
                    htmlType="submit"
                    loading={loading}
                    icon={<UploadOutlined />}
                    size="large"
                    style={{
                      background: 'linear-gradient(135deg, rgba(102, 126, 234) 0%, rgba(118, 75, 162) 100%)',
                      border: 'none',
                      color: 'white',
                      fontWeight: 'bold'
                    }}
                  >
                    发布种子
                  </Button>
                  <Button
                    size="large"
                    icon={<EyeOutlined />}
                    onClick={() => setPreviewTab('2')}
                  >
                    预览
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Card>
        </TabPane>
        <TabPane tab="预览" key="2">
          <Card>
            <div style={{ display: 'flex', marginBottom: 24 }}>
              <div style={{ marginRight: 24 }}>
                <Card
                  cover={<img alt="封面" src={coverImage || 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'} style={{ width: 300, height: 'auto' }} />}
                  style={{ width: 300 }}
                />
              </div>

              <div style={{ flex: 1 }}>
                <Title level={2}>{form.getFieldValue('title') || '未设置标题'}</Title>

                <Space style={{ marginBottom: 16 }} wrap>
                  <Tag color="blue">{form.getFieldValue('classification') || '未设置分类'}</Tag>
                  {(() => {
                    const promotion = form.getFieldValue('promotion');
                    if (promotion === 'double_upload') {
                      return <Tag color="green">⬆️ 双倍上传量</Tag>;
                    } else if (promotion === 'free_download') {
                      return <Tag color="orange">🆓 下载量免费</Tag>;
                    } else {
                      return <Tag color="default">🚫 无促销</Tag>;
                    }
                  })()}
                </Space>

                {form.getFieldValue('comment') && (
                  <div style={{ marginBottom: 16 }}>
                    <Title level={4}>描述</Title>
                    <Paragraph>{form.getFieldValue('comment')}</Paragraph>
                  </div>
                )}

                <div style={{ marginTop: 24 }}>
                  <Button type="primary" icon={<UploadOutlined />} size="large" onClick={() => setPreviewTab('1')}>
                    返回编辑
                  </Button>
                </div>
              </div>
            </div>


          </Card>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default UploadTorrent; 